import { inject, nextTick, onMounted, onUnmounted, reactive, watch } from 'vue'
import { Viewer } from '@/types'
import { Widget } from '@/models'

/** 弹出层类型 */
export enum PopoverType {
  /** 签章切换 */
  SIGN_CHANGE = 'sign-change',

  /** 签章规格 */
  SIGN_SPEC = 'sign-spec',

  /** 日期章设置 */
  DATE_SIGN_SET = 'date-sign-set',

  /** 批量应用 */
  BATCH_APPLY = 'batch-apply',

  /** 图片裁剪 */
  IMAGE_CROP = 'image-crop'
}

/** 弹出层状态 */
export type PopoverState = ReturnType<typeof useWidgetPopover>

/** 控件弹出层 */
export default function useWidgetPopover() {
  /** 合同控件 */
  const viewer = inject('Viewer') as Viewer

  const state = reactive({
    /** 当前弹出层类型 */
    type: null as PopoverType | null,

    /** 操作的控件 */
    widget: null as null | Widget,

    /** 触发节点 */
    ref: null as null | undefined | HTMLElement,

    /** 操作回调 */
    callback: null as null | ((...rest: any[]) => void),

    /** 合同控件 */
    viewer,

    /** 打开弹出层 */
    async open(type: PopoverType, el: HTMLElement | null, widget: Widget, callback?: () => void) {
      state.close()

      await nextTick()

      state.type = type
      ;(state.widget as Widget) = widget
      state.ref = el
      state.callback = callback || null
    },

    /** 关闭弹出层 */
    close() {
      state.type = null
      state.widget = null
      state.ref = null
      state.callback = null
    }
  })

  viewer
    // 监听弹出层打开 事件
    .$on('popover-open', (type: PopoverType, el: HTMLElement | null, widget: Widget, callback: () => void) =>
      state.open(type, el, widget, callback)
    )
    // 控件关闭时关闭弹出层
    .$on('widget-remove', state.close)

  /** 页码切换、文档切换时关闭弹出层 */
  watch([() => viewer.scroll.pageIndex, () => viewer.doc.id], state.close)

  /** 开始拖拽时关闭弹出层 */
  onMounted(() => document.addEventListener('dragstart', state.close))

  onUnmounted(() => document.removeEventListener('dragstart', state.close))

  return state
}
